package info.leetcode.answer.Array.TwoDimensionalArray.specific;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 螺旋矩阵 II
 * @date 2024/2/23 17:25
 */
public class GenerateMatrix {
    public static void main(String[] args) {
        int n = 3;
        int[][] result = generateMatrix(n);
        System.out.println(result);
    }

    private static int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        // 模拟指针方向
        int transverseIndex = 0 ;
        int directionIndex = 0 ;
        Boolean circulFlag = false ;
        int transverseFlag = 1 ;
        int directionFlag = 1 ;
        for (int i = 1; i <= n * n; i++) {
            try {
                if (result[transverseIndex][directionIndex] !=0){
                    throw  new IndexOutOfBoundsException();
                }
                if (circulFlag){
                    // 纵向
                    result[transverseIndex][directionIndex] = i ;
                    transverseIndex += transverseFlag;

                }else{
                    result[transverseIndex][directionIndex] = i ;
                    directionIndex += directionFlag;
                }
            }catch (IndexOutOfBoundsException e){
                i--;
                if (circulFlag){
                        // 转向
                        circulFlag = !circulFlag ;
                        transverseIndex -= transverseFlag;
                        transverseFlag *= -1 ;
                        directionIndex += directionFlag;
                    }else {
                        circulFlag = !circulFlag ;
                        directionIndex -= directionFlag;
                        directionFlag *= -1 ;
                        transverseIndex += transverseFlag;
                    }
            }

        }
        return result;
    }
}
